import axios from 'axios'
import Vue from 'vue'
import router from '@/router'
import store from '@/store'

const service = axios.create({
  baseURL: 'http://localhost:3000',
  timeout: 15000,
  withCredentials: true
})

// 全局请求拦截器
service.interceptors.request.use(
  (config) => {
    return config
  },
  (error) => {
    router.push({ path: '/error' })
    return Promise.reject(error)
  }
)
// 全局响应拦截器
service.interceptors.response.use(
  (res) => {
    if (res.data.code === '401') {
      Vue.prototype.notifyError(res.data.msg)
      store.dispatch('setShowLogin', true)
    }
    if (res.data.code === '500') {
      router.push({ path: '/error' })
    }
    return res
  },
  (error) => {
    router.push({ path: '/error' })
    return Promise.reject(error)
  }
)

Vue.prototype.$axios = service
